import { getISOString, getIsoDurationInfo } from "../utils";
import Select from "../../Select";
import React, { useEffect, useState } from "react";
import InputNumber from "./InputNumber";
import { useStyles } from "./style";
import { DurationUnitOption, PresetValue } from "../type";

interface DurationInputProps {
  selectedTimeMark?: string;
  setSelectedTimeMark: (value?: string) => void;
  presetItems: PresetValue[];
  durationUnitOptions: DurationUnitOption[];
}

function DurationInput({
  selectedTimeMark,
  setSelectedTimeMark,
  presetItems,
  durationUnitOptions,
}: DurationInputProps) {
  const classes = useStyles();
  const defaultSelectedOpt = durationUnitOptions[0].value;
  const [selectedOpt, setSelectedOpt] = useState<string>(defaultSelectedOpt);
  const [customizeInputVal, setCustomizeInputVal] = useState<
    number | undefined
  >(undefined);

  const handleInputChange = (value: number) => {
    const iso = getISOString(value, selectedOpt);
    setCustomizeInputVal(value);
    setSelectedTimeMark(iso);
  };

  const handleOptChange = (value: string) => {
    const iso = getISOString(customizeInputVal, value);
    setSelectedOpt(value);
    setSelectedTimeMark(iso);
  };

  useEffect(() => {
    const isPresetItem =
      presetItems.findIndex((item) => item === selectedTimeMark) > -1;
    if (!selectedTimeMark || isPresetItem) {
      setCustomizeInputVal(undefined);
      setSelectedOpt(selectedOpt || defaultSelectedOpt);
      return;
    }

    const { value, unit } = getIsoDurationInfo(selectedTimeMark);
    customizeInputVal !== value && setCustomizeInputVal(value);
    selectedOpt !== unit && setSelectedOpt(unit);
  }, []);

  return (
    <div className={classes.inputContainer}>
      <InputNumber
        onChange={handleInputChange}
        min={0}
        max={Number.MAX_VALUE}
        value={customizeInputVal}
      />
      <Select
        value={selectedOpt}
        className={classes.resetSelect}
        onChange={handleOptChange}
        options={durationUnitOptions}
      />
    </div>
  );
}

export default DurationInput;
